layui.define(['jquery', 'layuiFastHelper', 'form', 'table'], function (exports) {
    "use strict";

    let form = layui.form;
    let $ = layui.jquery;
    let layuiFastHelper = layui.layuiFastHelper;
    let table = layui.table;

    // 表格搜索组件
    var layuiFastTableSearch = {
        renderFormToggle: function (options) {
            var defaultsOpt = {
                isExpand: false,
                prefixIcon: "layui-icon",
                toggleIcon: ['layui-icon-down', 'layui-icon-up'],
                toggleText: ['展开', '折叠'],
                min: 1
            }
            var opt = $.extend({}, defaultsOpt, options);
            var elem = opt.elem; // 绑定的表单元素,必填
            var min = opt.min; // 最小显示数,默认显示一行
            var isExpand = opt.isExpand; // 初始展开
            var prefixIcon = opt.prefixIcon + " "; // 图标前缀
            var toggleIcon = opt.toggleIcon; // 折叠和展开时的图标类[unExpandIcon, ExpandIcon]
            var toggleText = opt.toggleText; // 折叠和展开时的文本

            var eleDOM = $(elem + " .layui-inline");
            var firstElTop = eleDOM.first().offset().top;
            var targetEl = eleDOM.filter(function (index) {
                var isGtMin = (index + 1) > min;
                var isGtFirstElTop = $(this).offset().top > firstElTop;
                var isNeqLast = (index + 1) != eleDOM.length;
                return min ? isGtMin && isNeqLast : isGtFirstElTop && isNeqLast;
            });

            var unExpandIcon = prefixIcon + toggleIcon[0];
            var expandIcon = prefixIcon + toggleIcon[1];
            var unExpandText = toggleText[0];
            var expandText = toggleText[1];
            var btnSelector = elem + " .expand";
            $(btnSelector).append("<i></i>")
            if (targetEl.length > 0) {
                if (isExpand) {
                    $(btnSelector).prepend("<span>" + expandText + "</span>");
                    $(btnSelector + ">i").addClass(expandIcon);
                } else {
                    $(btnSelector).prepend("<span>" + unExpandText + "</span>")
                    $(btnSelector + ">i").addClass(unExpandIcon)
                    targetEl.addClass("layui-hide");
                }
                $(btnSelector).click(function () {
                    isExpand = !isExpand;
                    if (isExpand) {
                        $(btnSelector + ">span").html(expandText);
                        $(btnSelector + ">i").removeClass(unExpandIcon).addClass(expandIcon);
                        targetEl.removeClass("layui-hide")
                    } else {
                        $(btnSelector + ">span").html(unExpandText);
                        $(btnSelector + ">i").removeClass(expandIcon).addClass(unExpandIcon);
                        targetEl.addClass("layui-hide")
                    }
                })
            }
        },
        render: function (id) {
            layuiFastTableSearch.renderFormToggle({elem: '#' + id + 'layuiFastTableSearchForm'});
            form.render();
            layuiFastHelper.laydaterange({elem: ".table-search-laydaterange"});
        },
        bindevent: function () {
            // 搜索表单中弹窗事件
            $(document).on('click', ".btn-layui-fast-table-search-dialog", function (e) {
                var that = this;
                layuiFastHelper.open($(this).attr('title') || $(this).data('title'), $(this).data('url'), {
                    callback: function (data) {
                        $('#' + $(that).data('input-id')).val(data).trigger("change");
                    }
                });
                e.stopImmediatePropagation();
            });
            // 提交
            form.on('submit(layuiFastTableSearchFormSubmit)', function (data) {
                var fields = data.field; // 获取表单全部字段值
                var params = {
                    filters: {},
                    ops: {},
                };
                for (const fieldsKey in fields) {
                    var key = fieldsKey.split('-');
                    if (key[0] == 'ops') {
                        var name = key[1];
                        var op = fields[fieldsKey];
                        var value = fields[name];
                        // 范围查询用逗号拼接开始值和结束值
                        if (fields[name + '[0]'] !== undefined && fields[name + '[1]'] !== undefined) {
                            value = [];
                            if (fields[name + '[0]']) {
                                value[0] = fields[name + '[0]'];
                            }
                            if (fields[name + '[1]']) {
                                value[1] = fields[name + '[1]'];
                            }
                            value = value.join(',');
                        }
                        if (op == 'IN') {
                            value = value.replace(/]|\r/g, ',');
                        }
                        // 过滤空值
                        if (value === '') {
                            continue;
                        }
                        params.ops[name] = op;
                        params.filters[name] = value;
                    }
                }
                // 此处可执行 Ajax 等操作
                table.reload($(this).parents('form').data('table-id'), {
                    where: params,
                    page: {
                        curr: 1,
                    },
                });
                return false; // 阻止默认 form 跳转
            });
            // 重置
            $(document).on('click', '.layuiFastTableSearchForm button[type="reset"]', function () {
                table.reload($(this).parents('form').data('table-id'), {
                    where: {},
                    page: {
                        curr: 1,
                    },
                });
            })
        },
        api: {
            input: {
                text: function (row) {
                    return '<input autocomplete="off" type="text" class="layui-input" value="" name="' + row.field + '" placeholder="' + (row.placeholder || row.title) + '" ' + (row.extend || '') + ' >';
                },
                textarea: function (row) {
                    return '<textarea name="' + row.field + '" placeholder="' + (row.placeholder || '一行一个') + '" class="layui-textarea" ' + (row.extend || '') + ' ></textarea>';
                },
                daterange: function (row) {
                    return '<div class="layui-input-wrap">' +
                        '       <input autocomplete="off" type="text" class="layui-input table-search-laydaterange" value="" name="' + row.field + '" placeholder="' + (row.placeholder || '请选择') + '" ' + (row.extend || '') + ' >' +
                        '       <div class="layui-input-suffix">' +
                        '           <i class="layui-icon layui-icon-date"></i>' +
                        '       </div>' +
                        '</div>';
                },
                between: function (row) {
                    return '<div>' +
                        '      <div class="layui-col-xs5">' +
                        '        <input autocomplete="off" type="number" value="" name="' + row.field + '[0]" placeholder="' + (row.placeholder || row.title) + '" autocomplete="off" class="layui-input" ' + (row.extend || '') + ' >' +
                        '      </div>' +
                        '      <div style="margin: 0;text-align:center;" class="layui-col-xs2 layui-form-mid">-</div>' +
                        '      <div class="layui-col-xs5">' +
                        '        <input autocomplete="off" type="number" value="" name="' + row.field + '[1]" placeholder="' + (row.placeholder || row.title) + '" autocomplete="off" class="layui-input" ' + (row.extend || '') + ' >' +
                        '      </div>' +
                        '</div>';
                },
                select: function (row) {
                    var options = [];
                    row.placeholder = row.placeholder || '直接选择或者搜索选择';
                    options.push('<option value="">' + row.placeholder + '</option>')
                    for (var searchDataKey in row.searchData) {
                        options.push('<option value="' + searchDataKey + '">' + row.searchData[searchDataKey] + '</option>')
                    }
                    return '<select name="' + row.field + '" lay-search="" ' + (row.extend || '') + ' >' + options.join('') + '</select>';
                },
                selectMultiple: function (row) {
                    var options = [];
                    row.placeholder = row.placeholder || '请选择';
                    options.push('<option value="">' + row.placeholder + '</option>')
                    for (var searchDataKey in row.searchData) {
                        options.push('<option value="' + searchDataKey + '">' + row.searchData[searchDataKey] + '</option>')
                    }
                    return '<select xm-select="select1" name="' + row.field + '" ' + (row.extend || '') + ' >' + options.join('') + '</select>';
                },
                dialog: function (row) {
                    return '<div class="layui-input-group">' +
                        '    <input id="' + row.field + 'layuiFastTableSearchDialog" style="border-radius: 4px 0 0 4px;" name="' + row.field + '" type="text" placeholder="' + (row.placeholder || '请选择') + '" class="layui-input">' +
                        '    <div data-input-id="' + row.field + 'layuiFastTableSearchDialog" data-url="' + row.searchData.url + (row.searchData.url.match(/(\?|&)+/) ? "&isSelectDialog=" : "?isSelectDialog=") + '1" title="' + row.searchData.title + '" class="layui-input-split layui-input-suffix btn-layui-fast-table-search-dialog" style="border-radius: 0 4px 4px 0;cursor: pointer;">' +
                        '    <i class="layui-icon layui-icon-layer"></i>' +
                        '    </div>' +
                        '</div>';
                }
            },
            filtersFormatter: function (row) {
                var ops = (row.ops || '=').toUpperCase();
                if (typeof row.searchData === 'function') {
                    return row.searchData(row)
                }
                switch (ops) {
                    case 'RANGE':
                        return layuiFastTableSearch.api.input.daterange(row);
                    case 'BETWEEN':
                        return layuiFastTableSearch.api.input.between(row);
                    case 'IN':
                        if (row.searchData) {
                            return layuiFastTableSearch.api.input.selectMultiple(row)
                        }
                        return layuiFastTableSearch.api.input.textarea(row);
                    case 'DIALOG':
                        return layuiFastTableSearch.api.input.dialog(row);
                    case 'LIKE':
                        row.placeholder = row.placeholder === undefined ? '模糊查询' : row.placeholder;
                        return layuiFastTableSearch.api.input.text(row);
                    default:
                        if (row.searchData) {
                            return layuiFastTableSearch.api.input.select(row)
                        }
                        return layuiFastTableSearch.api.input.text(row);
                }
            },
            opsFormatter: function (row) {
                var ops = (row.ops || '=').toUpperCase();
                if (ops == 'DIALOG') {
                    // 将弹窗查询的条件改成IN
                    ops = 'IN';
                }
                var op = 'ops-' + row.field;
                return '<input type="hidden" name="' + op + '" value="' + ops + '">';
            },
            render: function (id, rows) {
                var formItems = [];
                for (let i = 0; i < rows.length; i++) {
                    var row = rows[i]
                    if (row.ops === false) {
                        continue;
                    }
                    formItems.push('<div class="layui-form-item layui-inline">' +
                        '   <label class="layui-form-label">' + row.title + '</label>' +
                        '   <div class="layui-input-inline">' + layuiFastTableSearch.api.filtersFormatter(row) + layuiFastTableSearch.api.opsFormatter(row) + '</div>' +
                        '</div>');
                }

                $('#' + id).before('<form data-table-id="' + id + '" id="' + id + 'layuiFastTableSearchForm" class="layui-form layuiFastTableSearchForm" action="">' +
                    '            <div class="layui-form-item">' + formItems.join('') +
                    '                <div class="layui-form-item layui-inline layui-col-md-offset1">' +
                    '                    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-submit lay-filter="layuiFastTableSearchFormSubmit"><i class="layui-icon layui-icon-search"></i> 查询</button>' +
                    '                    <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm"><i class="layui-icon layui-icon-refresh"></i> 重置</button>' +
                    '                    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm expand"></button>' +
                    '                </div>' +
                    '            </div>' +
                    '        </form>');
                layuiFastTableSearch.render(id);
                layuiFastTableSearch.bindevent();
            }
        },
    };

    exports('layuiFastTableSearch', layuiFastTableSearch)
});